package com.danbay.cloud.device.service;

import com.danbay.cloud.device.api.dto.ResponseObject;
import com.danbay.cloud.device.api.dto.ResultEnum;
import com.danbay.cloud.device.api.service.IDeviceOfflineDataService;
import com.danbay.cloud.device.constant.DeviceCommonConstant;
import com.danbay.cloud.device.dto.DeviceOfflineDto;
import com.danbay.cloud.device.dto.DeviceOfflineListDto;
import com.danbay.framework.exception.BusinessException;
import com.danbay.framework.utils.ArrayUtils;
import com.danbay.framework.utils.DateUtils;
import com.danbay.framework.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yangyanchen on 2018/1/15
 *         Copyright © 2016 －2017 旦倍科技
 */
@Slf4j
@Service
public class DeviceOfflineDataService implements IDeviceOfflineDataService{

    private final Integer EXPIRE_TIME_COUNT =  0;

    @Autowired
    private DeviceCacheService deviceCacheService;

    @Override
    public ResponseObject getOfflineDeviceDetail(String homeAddress) throws BusinessException {
        ResponseObject responseObject = new ResponseObject();
        DeviceOfflineListDto deviceOfflineListDto = deviceCacheService.getDeviceOfflineList(DeviceCommonConstant.DEVICE_OFF_LINE_KEY);
        if (ArrayUtils.isNullOrEmpty(deviceOfflineListDto.getDeviceOfflineDtoList())) {
            responseObject.setCodeMessage(ResultEnum.FAILED);
            responseObject.setResult("");
            return responseObject;
        }
        List<DeviceOfflineDto> offlineList = deviceOfflineListDto.getDeviceOfflineDtoList().stream().filter(
                deviceOfflineDto ->
                        Days.daysBetween(
                                DateUtils.parse2LocalDate(deviceOfflineDto.getLastActiveTime())
                                , LocalDate.now()).getDays()  >= EXPIRE_TIME_COUNT
        ).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(homeAddress)) {
            offlineList = offlineList.stream().filter(deviceOfflineDto ->
                    deviceOfflineDto.getHomeAddress().contains(homeAddress)
            ).collect(Collectors.toList());
        }
        responseObject.setCodeMessage(ResultEnum.SUCCESS);
        responseObject.setResult(offlineList);
        return responseObject;
    }

}
